/**
 * 封装axios，增加request拦截器，将每次请求的header增加token
 * 增加response拦截器，非正常返回提示错误消息和session过期提示重新登录
 */
import axios from 'axios'
import { getToken } from './token'
import _this from '@/main.js'

// 创建axios实例
const $axios = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 30 * 1000
})

// request拦截器
$axios.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers.Authorization = getToken()
    }
    config.headers['Content-Type'] = 'application/json'
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response拦截器
$axios.interceptors.response.use(
  response => {
    const { data } = response
    if (data.code === 1000) {
      return data
    } else {
      if (data.code > 2000 && data.code < 3000) {
        // 跳转到登录页
        _this.$router.push('/login')
      } else {
        return new Promise().reject('error')
      }
    }
  },
  error => {
    return Promise.reject(error)
  }
)

// 自定义封装上传文件函数
$axios.upload = (url, file, params) => {
  const param = new FormData()
  param.append('file', file)
  param.append('params', params)
  const config = { headers: { 'Content-Type': 'multipart/form-data' } }
  return $axios.post(url, param, config)
}
export default $axios
